package chatstuff;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Parser {

	public static final String joinsRoom = "joins the room";
	public static final String leavesRoom = "leaves the room";

	public static String filterUtterance(String string, String charsToIgnore) {
		String filtered = "";

		StringTokenizer strTok = new StringTokenizer(string, charsToIgnore);

		while (strTok.hasMoreTokens()) {
			filtered += strTok.nextToken();
		}

		return filtered;
	}

	public static ArrayList<Utterance> parseDocument(String filePath) {
		ArrayList<Utterance> utterances = new ArrayList<Utterance>();

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;

		String team;
		String genid;
		String ref;
		String nickname;
		String utterance;

		try {

			db = dbf.newDocumentBuilder();

			Document dom = db.parse(new File(filePath));

			Element root = dom.getDocumentElement();

			team = root.getAttribute("team");

			NodeList nodeList = root.getElementsByTagName("Turn");

			for (int i = 0; i < nodeList.getLength(); i++) {
				Element iTurn = (Element) nodeList.item(i);

				nickname = iTurn.getAttribute("nickname");
				NodeList nl = iTurn.getElementsByTagName("Utterance");

				for (int nli = 0; nli < nl.getLength(); nli++) {
					Element crtUtterance = (Element) nl.item(nli);
					genid = crtUtterance.getAttribute("genid");
					ref = crtUtterance.getAttribute("ref");

					utterance = filterUtterance(crtUtterance.getTextContent(),
							".,:;!?");
					System.out.println(utterance);

					if (!utterance.equals(joinsRoom)
							&& !utterance.equals(leavesRoom))
						utterances.add(new Utterance(team, genid, ref,
								nickname, utterance, "-"));
				}

			}

		} catch (ParserConfigurationException e) {
			System.err.println("Parser configuration exception...");
			e.printStackTrace();
		} catch (SAXException e) {
			System.err.println("SAX exception...");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("IO exception...");
			e.printStackTrace();
		}
		return utterances;
	}

}
